<script>
    import URI from 'urijs';
    import TlImage from '@bixiao/ui/packages/image';
    import {Spin} from 'ant-design-vue'

    const mime = require('mime/lite');
    const Mime = require('mime/Mime');

    require('@bixiao/ui/lib/theme-chalk/image.css');
    const suffixMap = {};
    const suffixList = [
        '3ds',
        'aep',
        'ai',
        'c4d',
        'cdr',
        ['doc', 'docx'],
        'dwg',
        'fig',
        'gif',
        ['html', 'xml', 'dat', 'json', 'css', 'less', 'scss', 'js', 'xhtml'],
        // keynote类型
        ['keynote', 'key'],
        // 音频
        ['mp3', 'wav', 'wma', 'wmv', 'rm'],
        // 视频
        ['mp4', 'mov', 'avi'],
        'normal',
        'pdf',
        // ppt
        ['ppt', 'pptx'],
        // svg
        ['svg', 'eps'],

        'gif',
        'pr',
        'psd',
        'rp',
        'sketch',

        ['tiff', 'tif'],

        'txt',
        'xd',
        // 表格类型
        ['xlsx', 'xls'],
        'xmind',
        // 压缩类型
        ['zip', 'rar', 'tar', 'tgz', 'z']
    ]
    suffixList.forEach(value => {
        if (typeof value === "string") {
            suffixMap[`${value}/t-customize`] = [value];
        } else if (Array.isArray(value) && value.length > 0) {
            suffixMap[`${value[0]}/t-customize`] = value
        }
    })
    const my_mime = new Mime(suffixMap)

    import qs from 'qs'


    const imageMime = [
        'webp',
        'bmp',
        'png',
        'jpe',
        'jpeg',
        'jpg',
        'ico',
    ]

    export default {
        name: "tl-mimetype-icon",
        components: {
            [TlImage.name]: TlImage,
            [Spin.name]: Spin,
        },
        props: {
            errorSrc: {
                type: String,
                default: require('./assets/error.png')
            },
            mimeType: String,
            suffixType: String,
            src: String,
            fit: String,
            lazy: {
                type: Boolean,
                default: false
            },
            scrollContainer: [String, HTMLElement],
            previewSrcList: {
                type: Array,
                default: () => []
            },
            zIndex: {
                type: Number,
                default: 2000
            },
            getFileName: Function,
        },
        data() {
            return {}
        },
        render(h) {
            const $propsOptions = this.$propsOptions;
            let previewSrcList = Array.isArray($propsOptions.previewSrcList) ? $propsOptions.previewSrcList : [];
            if (this.$src === this.src && !previewSrcList.includes(this.src)) {
                previewSrcList.push(this.src)
            }
            return (
                <tl-image class={[`tl-mimetype-icon`, {
                    'tl-mimetype-img': this.$src === this.src,
                    'cursor-pointer': this.fileType === 'pdf'
                }]}
                          src={this.$src}
                          fit={$propsOptions.fit}
                          lazy={$propsOptions.lazy}
                          scrollContainer={$propsOptions.scrollContainer}
                          previewSrcList={previewSrcList}
                          zIndex={$propsOptions.zIndex}
                          getFileName={$propsOptions.getFileName}
                          onClick={this.onClick}
                          onError={this.onError}
                          onLoad={() => this.$emit('load', ...arguments)}>
                    <template slot="error">
                        <slot name="error">
                            <img class="tl-image__inner" style="object-fit: cover;"
                                 src={this.errorSrc}/>
                        </slot>
                    </template>
                    <template slot="placeholder">
                        <div class="tl-mimetype-icon__placeholder">
                            <a-spin/>
                        </div>
                    </template>
                </tl-image>
            )
        },
        computed: {
            $propsOptions() {
                const $props = this.$props
                return Object.assign(
                    {},
                    // 我们从父级添加所有的监听器
                    $props,
                    {src: null}
                )
            },
            fileType() {
                const src = this.src;
                if (!src) return 'unknown';
                const url = new URI(src);
                const mimeType = this.mimeType;
                const suffix = url.suffix() || (mimeType && mime.getExtension(mimeType));
                const my_suffix = my_mime.getType(suffix);
                if (my_suffix) return my_suffix.split('/')[0];
                return suffix || 'unknown';
            },
            $src() {
                const suffixType = this.suffixType || 'svg';
                let fileType = this.fileType;
                const mimeType = this.mimeType;
                const reg = new RegExp(`^(${imageMime.join('|')})$`, 'i');
                if (reg.test(fileType) || /^image\//.test(this.mimeType)) return this.src;
                else if (mimeType === 'document') fileType = 'document';
                return `https://res.tuoluocard.com/bixiao-web-static/mimetype/${suffixType}/${fileType}.${suffixType}`
            },

        },
        methods: {
            onError() {
                this.isError = true;
                this.$emit('error', ...arguments)
            },
            onClick() {
                if (this.fileType === 'pdf') {
                    const query = qs.stringify({file: this.src})
                    window.open(`https://res.tuoluocard.com/bixiao-web-static/web/pdf/generic/web/viewer.html?${query}`, '_blank')
                }
            }
        }
    }
</script>

<style scoped lang="scss">
    .tl-mimetype-icon__placeholder {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
    }
</style>
